#!/bin/bash

set -eu

function verify_hms_dir () {
	local hmsdir="$1"
	# verify that the directory argument is
	# the root source directory of hms,
	# with a couple of very simple tests
	if [ ! -d "${hmsdir}/mesh" ] || [ ! -d "${hmsdir}/solverBase" ]; then
		echo "Error: directory is not the hms source directory!"
		echo "Directory: ${hmsdir}"
		exit
	fi
}

verify_hms_dir "${hmsdir}"

builddir_rel="${hmsdir}/build/Release"
builddir_deb="${hmsdir}/build/Debug"

hmspath_rel="${builddir_rel}/bin/hms"
hmspath_deb="${builddir_deb}/bin/hms"


# Custom 'select' implementation that allows *empty* input.
# First argument should be true or false,
# for whether to output the option index or the option string,
# with "true" for the index and "false" for the string.
# Pass the options as individual arguments after that.
# Example:
#    choice=$(get_user_choice_def false 'one' 'two' 'three')
get_user_choice_def() {
    returnIndex=${1}
    shift 1

    local i numItems=$#

    # mark default option with this string
    local defstr="[default] "

    # Print numbered menu items, based on the arguments passed.
    for (( i=1; i<=$#; ++i )); do
        printf '%i) %s%s\n' $i "${defstr}" "${@:$i:1}"
        defstr=""
    done >&2 # Print to stderr, as `select` does.

    # Prompt the user for the index of the desired item.
    while :; do
        printf %s "${PS3-#? }" >&2 # Print the prompt string to stderr, as `select` does.
        read -r index
        # Make sure that the input is either empty or that a valid index was entered.
        [[ -z $index ]] && break  # empty input
        (( index >= 1 && index <= numItems )) 2>/dev/null || \
        { echo "${index} is not a valid choice. Please the number of one of the options above." >&2; continue; }
        break
    done
    # use first option as default
    if [[ -z $index ]]; then index=1; fi
    # and print it
    printf -- " -> Using option %i) %s\n" $index "${@:$index:1}" >&2

    # Output the selected item, either as index or as option string
    if [ $returnIndex = true ]; then
        echo $(( $index - 1))
    else
        printf %s "${@:$index:1}"
    fi
}

function get_n_threads_build() {
    maxThreads=$(lscpu -p | grep -c "^[0-9]")
    echo $(( maxThreads - 2 >= 1 ? maxThreads - 2 : 1 ))
}
